package com.xb.ai.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xb.ai.annotation.Login;
import com.xb.ai.constant.ErrorMessage;
import com.xb.ai.entity.vo.ChatVo;
import com.xb.ai.entity.vo.MessageVO;
import com.xb.ai.common.Result;
import com.xb.ai.exception.BusinessException;
import com.xb.ai.repository.ChatHistoryRepository;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {

    @Resource
    private ChatHistoryRepository chatHistoryRepository;

    @Resource
    private ChatMemory chatMemory;

    @GetMapping
    public Result<List<ChatVo>> getChatIds(Long userId) {
        verifyUserLogin(userId);
        return Result.success(chatHistoryRepository.getChatList(userId));
    }

    @Login
    @GetMapping("/{chatId}")
    public Result<List<MessageVO>> getChatHistory(@PathVariable("chatId") String chatId,
                                                  @RequestParam("userId") Long userId) {
        verifyUserLogin(userId);
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if (messages == null) {
            return Result.success(new ArrayList<>());
        }
        return Result.success(messages.stream().map(MessageVO::new).toList());
    }

    /**
     * 验证用户是否登录
     * @param userId 用户传的id
     */
    public void verifyUserLogin(Long userId) {
        if (userId == null) {
            throw new BusinessException(ErrorMessage.NOT_LOGIN_ERROR);
        }
        long userLoginId = StpUtil.getLoginIdAsLong();
        if (userId != userLoginId) {
            throw new BusinessException(ErrorMessage.NO_AUTH_ERROR);
        }
    }
}
